<template>
  <w-modal
    ref="WModal"
    title="身份证识别"
    :ok-text="identifyArr.length > 0 ? '清除' : '识别'"
    :ok-type="identifyArr.length > 0 ? 'danger' : 'primary'"
    @ok="okClick"
  >
    <div class="from-box">
      <a-form
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-item label="身份证图片">
          <image-up ref="WImageUp" />
        </a-form-item>
        <a-form-item label="正、反面">
          <a-select v-model="idCardType">
            <a-select-option key="front" value="front">
              头像面
            </a-select-option>
            <a-select-option key="back" value="back">
              国徽面
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </div>
    <div v-if="identifyArr.length">
      <br>
      <p v-for="(v, k) in identifyArr" :key="k">
        {{ v.key }}：{{ v.words }}
      </p>
    </div>
  </w-modal>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Api } from '@/config/api'
import ImageUp from '@/components/global/imageUp/server'
import WModal, { ModalComType } from '@/components/global/modal'

@Component({
  name: 'WebToolImageIdentifyIDCard',
  components: {
    ImageUp,
    WModal
  }
})
export default class WebToolImageIdentifyIDCard extends Vue {
  // 识别出的文字
  identifyArr: Array<any> = [];
  // 身份证类型
  idCardType = 'front';

  // 图片识别按钮点击
  imageInentify () {
    (this.$refs.WModal as ModalComType).showLoading();
    (this.$refs.WImageUp as any)
      .upImage()
      .then((data: any) => {
        this.$wAxios
          .$post(Api.baidu.idcardIdentify, {
            localPath: data.filepath,
            isFront: this.idCardType === 'front'
          })
          .then((data) => {
            this.identifyArr = []
            if (data.words_result) {
              for (const ket in data.words_result) {
                this.identifyArr.push({
                  key: ket,
                  words: data.words_result[ket].words
                })
              }
            } else {
              this.$message.error('没有识别出文字')
            }
          })
          .catch(() => {
            this.identifyArr = []
          })
          .finally(() => {
            (this.$refs.WModal as ModalComType).hideLoading()
          })
      })
      .catch((err: any) => {
        this.$message.error(err.msg);
        (this.$refs.WModal as ModalComType).hideLoading()
      })
  }

  /**
   * 显示弹窗
   */
  show () {
    (this.$refs.WModal as ModalComType).show()
  }

  /**
   * 清除按钮点击
   */
  clear () {
    this.identifyArr = [];
    (this.$refs.WImageUp as any).clear()
  }

  okClick () {
    if (this.identifyArr.length) {
      this.clear()
    } else {
      this.imageInentify()
    }
  }
}
</script>

<style scoped lang="less">
.from-box {
  position: relative;
  .type-option {
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
